import { createRouter, createWebHashHistory } from "vue-router";

import Index from "@/views/index/index.vue";

// 扩展 RouteMeta 类型
declare module "vue-router" {
  interface RouteMeta {
    title: string;
    needLogin?: boolean;
  }
}

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      name: "index",
      component: Index,
      redirect: "/home",
      children: [
        {
          path: "home",
          name: "home",
          component: () => import("@/views/index/home.vue"),
          meta: {
            title: "首页",
          },
        },
        {
          path: "cart",
          name: "cart",
          component: () => import("@/views/index/cart.vue"),
          meta: {
            title: "购物车",
            needLogin: true,
          },
        },
        {
          path: "center",
          name: "center",
          component: () => import("@/views/index/center.vue"),
          meta: {
            title: "个人中心",
            needLogin: true,
          },
        },
      ],
    },
    {
      path: "/detail/:id",
      name: "detail",
      component: () => import("@/views/detail/index.vue"),
      meta: {
        title: "详情",
      },
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login/index.vue"),
      meta: {
        title: "登录",
      },
    },
    {
      path: "/register",
      name: "register",
      component: () => import("@/views/register/index.vue"),
      meta: {
        title: "注册",
      },
      children: [
        {
          path: "step-1",
          name: "step-1",
          component: () => import("@/views/register/step-one.vue"),
          meta: {
            title: "注册-1",
          },
        },
        {
          path: "step-2",
          name: "step-2",
          component: () => import("@/views/register/step-two.vue"),
          meta: {
            title: "注册-2",
          },
        },
        {
          path: "step-3",
          name: "step-3",
          component: () => import("@/views/register/step-three.vue"),
          meta: {
            title: "注册-3",
          },
        },
      ],
    },
    {
      path: "/city",
      name: "city",
      component: () => import("@/views/city/index.vue"),
      meta: {
        title: "城市选择",
      },
    },
    {
      path: "/:pathMatch(.*)*",
      name: "NotFound",
      component: () => import("@/views/not-found/index.vue"),
      meta: {
        title: "404",
      },
    },
  ],
});

router.beforeEach((to) => {
  // 获取token
  const { token } = JSON.parse(localStorage.getItem("user") || "{}");

  // 需要登录又没有登录时，就需要做跳转
  if (to.meta.needLogin && !token) {
    return {
      name: "login",
      // 处理登录成功之后回到之前想要去的页面
      query: {
        redirect: to.fullPath,
      },
    };
  }
});

router.afterEach((to) => {
  document.title = to.meta.title;
});

export default router;
